#include "./windib.h"

using namespace MiniUI;
using namespace MiniUI::Type;

WinDIB::WinDIB()
: m_hDC(nullptr)
, m_hDIB(nullptr)
, m_lpByte(nullptr)
{
}

WinDIB::~WinDIB()
{
    if (m_hDIB)
    {
        ::DeleteObject(m_hDIB);
    }
    if (m_hDC)
    {
        ::DeleteDC(m_hDC);
    }
}

void WinDIB::Rebuild(int cx, int cy)
{
    CreateDevice();

    memset(&m_bmpInfo, 0, sizeof(m_bmpInfo));

    m_bmpInfo.bmiHeader.biSize = sizeof(m_bmpInfo.bmiHeader);
    m_bmpInfo.bmiHeader.biWidth = cx;
    m_bmpInfo.bmiHeader.biHeight = -cy;
    m_bmpInfo.bmiHeader.biPlanes = 1;
    m_bmpInfo.bmiHeader.biBitCount = 32;
    m_bmpInfo.bmiHeader.biSizeImage = cx * cy * 4;

    m_lpByte = nullptr;
    m_hDIB = ::CreateDIBSection(nullptr, &m_bmpInfo, DIB_RGB_COLORS, (void**)&m_lpByte, nullptr, 0);

    HGDIOBJ hOldObject = ::SelectObject(m_hDC, m_hDIB);
    ::DeleteObject(hOldObject);
}

void WinDIB::CopyBits(lpvoid pBits, const MiniRect& rcDst)
{
    ::SetDIBitsToDevice(m_hDC, 
        rcDst.left, rcDst.top, rcDst.Width(), rcDst.Height(),
        0, 0, 0, rcDst.Height(), 
        pBits, &m_bmpInfo, DIB_RGB_COLORS);
}

byte* WinDIB::GetData()
{
    return m_lpByte;
}

void WinDIB::CreateDevice()
{
    if (!m_hDC)
    {
        m_hDC = ::CreateCompatibleDC(nullptr);
    }
}